import 'dart:async';
import 'dart:convert';

import 'package:build/build.dart';

class JsonToLocalizationGenerator implements Builder {
  @override
  final buildExtensions = const {
    '.json': ['.g.dart'],
  };

  @override
  Future<void> build(BuildStep buildStep) async {
    final inputId = buildStep.inputId;
    final content = await buildStep.readAsString(inputId);
    final map = json.decode(content) as Map<String, dynamic>;

    final langCode = inputId.pathSegments.last.split('.').first;
    final className = 'MyTranslations${langCode[0].toUpperCase()}${langCode.substring(1)}';

    final buffer = StringBuffer();
    buffer.writeln('// GENERATED CODE - DO NOT MODIFY BY HAND');
    buffer.writeln("import 'my_localizations.dart';");
    buffer.writeln('class $className implements MyLocalizations {');

    for (final key in map.keys) {
      buffer.writeln('  @override');
      buffer.writeln('  String get $key => "${map[key]}";');
    }

    buffer.writeln('}');

    final outputId = inputId.changeExtension('.g.dart');
    await buildStep.writeAsString(outputId, buffer.toString());
  }
}

Builder jsonToLocalizationBuilder(BuilderOptions options) => JsonToLocalizationGenerator();
